<template>
  <div class="app-container">
    <div class="dialog_title">
      {{
        `受控主机ip：${rowInfo.skIp || ""}` +
        "&emsp;&emsp;" +
        `受控主机名称：${rowInfo.skName || ""}`
      }}
    </div>
    <el-form
      :model="queryParams"
      ref="queryParams"
      size="small"
      label-width="130px"
    >
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="软件名称">
            <el-input
              v-model="queryParams.softwareName"
              placeholder="请输入软件名称"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="是否自动化部署">
            <el-select
              v-model="queryParams.softwareType"
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="it in softwareTypeOptions"
                :key="it.value"
                :value="it.value"
                :label="it.label"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="small"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="small" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row class="mb8">
      <el-button
        type="primary"
        size="mini"
        @click="addSoftware"
        plain
        icon="el-icon-plus"
        >添 加</el-button
      >
      <el-button
        type="primary"
        size="mini"
        @click="autoDeploy"
        plain
        icon="el-icon-data-analysis"
        >自动化部署</el-button
      >
    </el-row>

    <el-table v-loading="loading" border :data="softwareList">
      <el-table-column
        label="软件名称"
        align="center"
        prop="softwareName"
        :show-overflow-tooltip="true"
        min-width="180"
      ></el-table-column>
      <el-table-column
        label="软件描述"
        align="center"
        prop="softwareDesc"
        :show-overflow-tooltip="true"
        min-width="430"
      ></el-table-column>
      <el-table-column
        label="是否自动化部署"
        align="center"
        prop="softwareType"
        :show-overflow-tooltip="true"
        width="150"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.softwareType == "1" ? "是" : "否" }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="部署时间"
        align="center"
        prop="createTime"
        :show-overflow-tooltip="true"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="120">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.softwareType == '2'"
            size="mini"
            icon="el-icon-edit"
            @click="updateSoftware(scope.row)"
            type="text"
            >修改</el-button
          >
          <el-button
            v-if="scope.row.softwareType == '2'"
            size="mini"
            icon="el-icon-delete"
            @click="delSoftware(scope.row)"
            type="text"
            >删除</el-button
          >
          <el-button
            v-if="scope.row.softwareType == '1'"
            :disabled="scope.row.softwareStatus == '0'"
            size="mini"
            type="text"
            icon="el-icon-video-play"
            @click="handleStart(scope.row)"
            >启动</el-button
          >
          <el-button
            v-if="scope.row.softwareType == '1'"
            :disabled="scope.row.softwareStatus == '1'"
            size="mini"
            type="text"
            icon="el-icon-switch-button"
            @click="handleStop(scope.row)"
            >停止</el-button
          >
          <el-button
            v-if="scope.row.softwareType == '1'"
            :disabled="scope.row.isInstall == '0'"
            size="mini"
            type="text"
            icon="el-icon-document-delete"
            @click="handleUninstall(scope.row)"
            >卸载</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      title="添加软件"
      :visible.sync="addVisible"
      width="700px"
      :before-close="addCancel"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        size="small"
        label-width="130px"
      >
        <el-form-item label="软件名称" prop="softwareName">
          <el-input
            v-model="form.softwareName"
            clearable
            style="width: 80%"
            placeholder="请填写软件名称"
            @blur="onBsp($event)"
          ></el-input>
        </el-form-item>
        <el-form-item label="软件描述" prop="softwareDesc">
          <el-input
            v-model="form.softwareDesc"
            type="textarea"
            clearable
            style="width: 80%"
            placeholder="请填写软件描述"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="addCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getSoftwareDescList,
  executeStopBat,
  executeUninsBat,
  executeStartBat,
  addHandleSoftware,
  updateHandleSoftware,
  deleHandleSoftware,
  getDistinctName,
} from "@/api/resource/sever-mange";
export default {
  data() {
    return {
      loading: false,
      softwareList: [],
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        rjlx: 1,
      },
      rowInfo: {},
      addVisible: false,
      form: {
        rjlx: 1,
      },
      typeOptions: [{ value: "1", label: "暂定类型" }],
      rules: {
        softwareName: [
          { required: true, message: "请输入模拟器名称", trigger: "blur" },
        ],
        softwareDesc: [
          { required: true, message: "请输入模拟器描述", trigger: "blur" },
        ],
      },
      softwareTypeOptions: [
        { value: "1", label: "是" },
        { value: "2", label: "否" },
      ],
    };
  },
  watch: {
    "$route.query.p": {
      handler(val) {
        if (val) {
          const param = JSON.parse(Buffer.from(val, "base64").toString());
          this.rowInfo.skName = decodeURI(param.skName);
          this.rowInfo.skIp = param.skIp;
        }
      },
      immediate: true,
    },
  },
  created() {
    this.getList();
  },
  mounted() {
    this.form.systemName = this.rowInfo.skName;
    this.form.systemIp = this.rowInfo.skIp;
  },
  methods: {
    onBsp(event) {
      getDistinctName({ softwareName: event.target.form[0].value }).then(
        (res) => {
          if (res.data) {
            this.$message.error("名字已重复");
          }
        }
      );
    },
    handleQuery() {
      this.getList();
    },
    resetQuery() {
      this.queryParams = {
        systemName: this.rowInfo.skName,
        systemIp: this.rowInfo.skIp,
        softwareName: "",
        softwareType: null,
      };
      this.handleQuery();
    },
    updateSoftware(row) {
      this.addVisible = true;
      this.form = JSON.parse(JSON.stringify(row));
    },
    delSoftware(row) {
      this.$confirm("确定删除此软件?", "提示", {
        type: "warning",
      })
        .then(() => {
          deleHandleSoftware(row).then((res) => {
            if (res.code == 200) {
              this.$message.success("删除成功");
              this.addVisible = false;
              this.getList();
            } else {
              this.$message.error("删除失败");
            }
          });
        })
        .catch(() => {});
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          getDistinctName({ softwareName: this.form.softwareName }).then(
            (res) => {
              if (res.data) {
                this.$message.error("名字已重复");
              } else {
                if (this.form.id !== undefined && this.form.id !== null) {
                  updateHandleSoftware(this.form).then((res) => {
                    if (res.code == 200) {
                      this.$message.success("修改成功");
                      this.addCancel();
                      this.getList();
                    } else {
                      this.$message.error("修改失败");
                    }
                  });
                } else {
                  addHandleSoftware(this.form).then((res) => {
                    if (res.code == 200) {
                      this.addCancel();
                      this.$message.success("新增成功");
                      this.getList();
                    } else {
                      this.$message.error(res.msg);
                    }
                  });
                }
              }
            }
          );
        }
      });
    },
    // 自动化部署
    autoDeploy() {
      // 解析跳转过来的参数 用于跳转部署页面
      let param = JSON.parse(
        Buffer.from(this.$route.query.p, "base64").toString()
      );
      // 拼软件部署需要的参数
      let autoParam = Buffer.from(
        JSON.stringify(Object.assign(param, { rjlx: 1 }))
      ).toString("base64");
      // 此时有受控端正在部署
      if (this.$store.state.permission.deployFlag) {
        // 判断当前的要跳转的id，是否是正在部署的受控端，是就跳转
        if (this.$store.state.permission.skID == param.skId) {
          this.$store.commit("SET_JUMP_FLAG", true);
          this.$router.push(`/resource/severMange/deploy?p=${autoParam}`);
        } else {
          this.$message.warning("有受控端正在部署，请等待部署完成");
        }
        return;
      }
      if (param.isOnline == "0") {
        this.$notify({
          title: "提示",
          // message: "受控端计算机处于离线状态",
          dangerouslyUseHTMLString: true,
          message: `<div>受控IP:${param.skIp}</div><div>受控主机名:${param.skName}</div>处于离线状态`,
          type: "warning",
        });
      }
      this.$store.commit("SET_JUMP_FLAG", true);
      this.$router.push(`/resource/severMange/deploy?p=${autoParam}`);
    },
    addSoftware() {
      this.addVisible = true;
    },
    addCancel() {
      // this.form = {
      //   systemName: this.rowInfo.skName,
      //   systemIp: this.rowInfo.skIp,
      //   softwareName: null,
      //   softwareDesc: null,
      //   tcpPort: null,
      //   sfType: null
      // }
      this.$refs.form.resetFields();
      this.addVisible = false;
    },
    getList() {
      this.queryParams.systemName = this.rowInfo.skName;
      this.queryParams.systemIp = this.rowInfo.skIp;
      this.loading = true;
      getSoftwareDescList(this.queryParams).then((res) => {
        this.softwareList = res.rows;
        this.loading = false;
      });
    },
    handleStart(row) {
      this.$confirm("确定要执行启动操作吗？", "警告", {
        type: "warning",
      })
        .then(() => {
          this.$notify.info({
            title: "执行中",
            message: "正在执行启动操作。。。",
            showClose: false,
            duration: 0,
          });
          executeStartBat(row.skSystemProcessId, {
            historyId: row.historyId,
            skSystemSoftwareId: row.id,
          }).then((res) => {
            if (res.code == 200) {
              this.$message.success("执行成功");
            } else {
              this.$message.error(res.msg);
            }
            this.getList();
            this.$notify.closeAll();
          });
        })
        .catch(() => {});
    },
    handleStop(row) {
      this.$confirm("确定要执行停止操作吗？", "警告", {
        type: "warning",
      })
        .then(() => {
          this.$notify.info({
            title: "执行中",
            message: "正在执行停止操作。。。",
            showClose: false,
            duration: 0,
          });
          executeStopBat(row.skSystemProcessId, {
            historyId: row.historyId,
            skSystemSoftwareId: row.id,
          }).then((res) => {
            if (res.code == 200) {
              this.$message.success("执行成功");
            } else {
              this.$message.error(res.msg);
            }
            this.getList();
            this.$notify.closeAll();
          });
        })
        .catch(() => {});
    },
    handleUninstall(row) {
      this.$confirm("确定要执行卸载操作吗？", "警告", {
        type: "warning",
      })
        .then(() => {
          this.$notify.info({
            title: "执行中",
            message: "正在执行卸载操作。。。",
            showClose: false,
            duration: 0,
          });
          executeUninsBat(row.skSystemProcessId, {
            historyId: row.historyId,
          }).then((res) => {
            if (res.code == 200) {
              this.$message.success("执行成功");
            } else {
              this.$message.error(res.msg);
            }
            this.getList();
            this.$notify.closeAll();
          });
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss" scoped>
.dialog_title {
  height: 32px;
  font-weight: 600;
  line-height: 32px;
  margin-left: 5px;
  margin-bottom: 10px;
  margin-top: 10px;
  padding-left: 5px;
  position: relative;
  color: #000;
  z-index: 0;

  border-radius: 16px;
  border: 1px solid #e8e9fb;
  box-shadow: 0 0 10px #e8e9fb;
  text-align: center;
  width: 600px;
  color: #12a3f5;

  &:before {
    content: "";
    width: 100%;
    height: 2px;
    background: #e8e9fb;
    position: absolute;
    top: 15px;
    left: 100%;
    background: linear-gradient(to right, #e8e9fb, rgba(255, 255, 255, 0));
  }
}
</style>
